package com.demo.java.OD51_100.OD98;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author bug菌
 * @Source 公众号：猿圈奇妙屋
 * @des： 【寻找身高相近的小朋友】问题
 * @url： https://blog.csdn.net/weixin_43970743/article/details/145662617
 */
public class OdMain {
    // 定义学生模型类
    static class StudentModel implements Comparable<StudentModel> {
        private int myHigh;  // 学生身高
        private int distance; // 与目标身高的差值

        // 构造函数
        public StudentModel(int myHigh, int distance) {
            this.myHigh = myHigh;
            this.distance = distance;
        }

        @Override
        public int compareTo(StudentModel stu) {
            // 先比较身高差值
            if (this.distance != stu.distance) {
                return this.distance - stu.distance;
            } else {
                // 如果身高差值相同，按身高升序排序
                return this.myHigh - stu.myHigh;
            }
        }
    }

    public static void main(String[] args) {
        try {
            Scanner s = new Scanner(System.in);
            String[] lines = s.nextLine().split(" ");
            int high = Integer.parseInt(lines[0]);  // 目标学生身高
            int num = Integer.parseInt(lines[1]);  // 班级同学数目
            String[] stuStrs = s.nextLine().split(" ");  // 班级学生身高
            List<StudentModel> resultList = new ArrayList<>();

            // 遍历班级学生，计算与目标学生身高的差值
            for (int j = 0; j < num; ++j) {
                int highTmp = Integer.parseInt(stuStrs[j]);
                resultList.add(new StudentModel(highTmp, Math.abs(high - highTmp)));
            }

            // 排序
            resultList.sort(null);

            // 输出排序后的学生身高
            for (int j = 0; j < resultList.size(); ++j) {
                String result = resultList.get(j).myHigh + " ";
                System.out.print(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("input error");
        }
    }
}